package com.example.database_bakup.schedule;


import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.log.Log;
import com.example.database_bakup.util.JdbcUtils;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Map;

@Component
@EnableScheduling
public class ScheduleTask {

    @Autowired
    private JdbcUtils jdbcUtils;

    @Autowired
    private Environment environment;

    @Value("${backup.url}")
    private String resourcePath;

    /**
     * 定时备份数据库信息
     */
//    @Scheduled(cron = "0 0 1 * * ?")
    @Scheduled(cron = "0/6 * * * * ?")
    public void backUpDataBase() {
        System.out.println("定时备份数据库" + LocalDate.now());
//        LoggerUtil.info("======执行定时器:定时备份数据库=======");
        String backUpPath = resourcePath;
//        String backUpPath = resourcePath+"/sql/" + Date.valueOf(LocalDate.now());
        File backUpFile = new File(backUpPath);
        if (!backUpFile.exists()) {
            backUpFile.mkdirs();
        }
        File dataFile = new File(backUpPath+"/primaryedu_"+Date.valueOf(LocalDate.now())+".sql");
        //拼接cmd命令
        StringBuffer sb = new StringBuffer();
        Map<String, String> dbInfo = jdbcUtils.getDBInfo();
        sb.append("mysqldump");
        sb.append(" -u"+dbInfo.get("userName"));
        sb.append(" -p"+dbInfo.get("passWord"));
        sb.append(" "+ dbInfo.get("dbName") +" > ");
        sb.append(dataFile);
//        LoggerUtil.info("======数据库备份cmd命令为："+sb.toString()+"=======");
        try {
            Process exec = Runtime.getRuntime().exec("cmd /c"+sb.toString());
            if (exec.waitFor() == 0){
//                LoggerUtil.info("======数据库备份成功，路径为："+dataFile+"=======");
            }
        } catch (Exception e) {
//            LoggerUtil.info("======数据库备份失败，异常为："+e.getMessage()+"=======");
        }
    }

    /**
     * 定时删除数据库备份文件，只保留最近一个星期
     */
    @Scheduled(cron = "0/6 * * * * ?")
    public void deleteBackUpDataBase() {
//        LoggerUtil.info("======执行定时器:定时删除备份数据库文件=======");
        String backUpPath = resourcePath;
//        String backUpPath = resourcePath+"/sql";
        File backUpFile = new File(backUpPath);
        if (backUpFile.exists()) {
            File[] files = backUpFile.listFiles();
            for (File file : files) {
                String fileName = file.getName(); //primaryedu_2023-06-28.bak
                String[] split = fileName.split("_");
                int length = split.length; //文件名称不对劲
                if(length == 1) {
                    file.delete();
                    continue;
                }
                String strDate = split[1].substring(0, 10);
                Date date1 = Date.valueOf(strDate);
                Date date2 = Date.valueOf(LocalDate.now());
                long betweenDay = DateUtil.between(date1, date2, DateUnit.DAY);
                if (betweenDay > 30) {
                    file.delete();
                }
            }
        }
    }







}
